package com.linkdood.app.web.rest;

import com.linkdood.app.annotation.Patch;
import com.linkdood.app.annotation.PatchRequestBody;
import com.linkdood.app.constants.ErrorCode;
import com.linkdood.app.domain.ThirdParty;
import com.linkdood.app.vm.AccountVM;
import com.linkdood.app.dto.OrganizationDTO;
import com.linkdood.app.dto.ThirdPartyDTO;
import com.linkdood.app.dto.ThirdPartyInfoDTO;
import com.linkdood.app.exception.GeneralException;
import com.linkdood.app.service.AccountService;
import com.linkdood.app.service.DdioCheckService;
import com.linkdood.app.service.OrganizationService;
import com.linkdood.app.service.ThirdPartyService;
import com.linkdood.app.service.UserService;
import com.linkdood.app.utils.ResourceUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 第三方平台配置
 *
 * @author hycao
 */
@Slf4j
@Controller
@RequestMapping("/api/thirdparties")
public class ThirdPartyResource {

    private final ThirdPartyService thirdPartyService;

    private final OrganizationService organizationService;

    private final UserService userService;

    private final AccountService accountService;

    private final DdioCheckService ddioCheckService;

    public ThirdPartyResource(ThirdPartyService thirdPartyService, OrganizationService organizationService,
                              UserService userService, DdioCheckService ddioCheckService,
                              AccountService accountService) {
        this.thirdPartyService = thirdPartyService;
        this.organizationService = organizationService;
        this.userService = userService;
        this.ddioCheckService = ddioCheckService;
        this.accountService = accountService;
    }

    @ApiOperation(value = "获取第三方平台总体信息数据")
    @GetMapping("/info/{id}")
    public ResponseEntity<ThirdPartyInfoDTO> getInfo(@PathVariable String id) {
        ThirdParty thirdParty = thirdPartyService.getById(id);
        ThirdPartyInfoDTO thirdPartyInfoDto = new ThirdPartyInfoDTO();
        thirdPartyInfoDto.setThirdPartyId(id);
        thirdPartyInfoDto.setThirdPartyName(thirdParty.getName());
        // 根据 第三方id 获取当前接入平台，拥有的部门数量和人员数量
        thirdPartyInfoDto.setOrgsNum(organizationService.countOrganization(id));
        thirdPartyInfoDto.setEmployeesNum(userService.countUser(id));
        return ResponseEntity.ok(thirdPartyInfoDto);
    }

    @ApiOperation(value = "获取第三方平台的配置信息详情")
    @GetMapping("/{id}")
    public ResponseEntity<?> getThirdParty(@PathVariable String id) {
        ThirdParty thirdParty = thirdPartyService.getThirdParty(id);
        return ResponseEntity.ok(thirdParty);
    }

    @ApiOperation(value = "获取第三方平台的配置信息列表")
    @GetMapping("/")
    public ResponseEntity<?> getThirdPartyList(@RequestParam(value = "thirdPartyId", required = false) String thirdPartyId) {
        List<ThirdParty> thirdParties = thirdPartyService.listThirdPartyByThirdPartyId(thirdPartyId);
        return ResponseEntity.ok(thirdParties);
    }

    @PreAuthorize("@ss.hasPermi('bxy:thirdparties:edit')")
    @ApiOperation(value = "更新第三方平台的配置信息")
    @Patch(service = ThirdPartyService.class)
    @PatchMapping("/{id}")
    public ResponseEntity<?> updateThirdParty(@PathVariable String id, @PatchRequestBody ThirdParty thirdParty) {
        thirdPartyService.updateThirdParty(thirdParty);
        return ResponseEntity.ok(ResourceUtil.success());
    }

    @ApiOperation(value = "删除指定 id 的第三方平台信息")
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteThirdParty(@PathVariable Long id) {
        thirdPartyService.removeById(id);
        return ResponseEntity.ok(ResourceUtil.success());
    }

    @PreAuthorize("@ss.hasPermi('bxy:department:index')")
    @ApiOperation(value = "获取指定平台下的组织信息")
    @GetMapping("/organization")
    public ResponseEntity<?> deleteThirdParty(@RequestParam(required = false) String thirdPartyId,
                                              @RequestParam(required = false) String parentOrgId) {
        if (StringUtils.isEmpty(thirdPartyId)) {
            thirdPartyId = thirdPartyService.getDefaultThirdParty().getId();
        }
        List<OrganizationDTO> result;
        if (parentOrgId == null) {
            result = organizationService.listOrganizationTrees(thirdPartyId);
        } else if (parentOrgId.isEmpty()) {
            result = organizationService.listRootOrganizations(thirdPartyId);
        } else {
            result = organizationService.listSonOrganizations(thirdPartyId, parentOrgId);
        }
        return ResponseEntity.ok(result);
    }

    @ApiOperation(value = "第三方 接口状态", notes = "第三方平台 服务器的接口状态")
    @GetMapping(value = "/{thirdPartyId}}/status")
    public ResponseEntity<?> getInterfaceStatus(@PathVariable String thirdPartyId) {
        AccountVM userAccount = accountService.getCurrentAccountInfo();
        AccountVM.InnerUser innerUser = userAccount.getUser();
        if (innerUser == null) {
            // TODO 如果没有绑定 user 的超管想要查询接口状态，无法获取sourceId
            throw new GeneralException("");
        }
        return ResponseEntity.ok(ddioCheckService.getDdioStatus(thirdPartyId, innerUser.getSourceId()));
    }
    @PreAuthorize("@ss.hasPermi('bxy:thirdparties:test')")
    @ApiOperation(value = "第三方平台接口连通性测试")
    @PostMapping(value = "/{thirdPartyId}/connectivity")
    public ResponseEntity<?> getServerStatus(@RequestBody ThirdPartyDTO thirdPartyDTO, @PathVariable String thirdPartyId) {
        ThirdParty thirdParty = thirdPartyService.getById(thirdPartyId);
        if (!"dood".equals(thirdParty.getName())) {
            throw new GeneralException(ErrorCode.ERROR_UNKNOWN_THIRD_PARTY_PLATFORM);
        }
        return ResponseEntity.ok(ddioCheckService.getStatus(thirdPartyDTO));
    }
}
